<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" inline>
                <el-row :gutter="10">
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="4">
                    <el-form-item>
                      <div class="search_label">资 产</div>
                      <v-select-s v-model="query.equipment_id" action="eqList" :query="{add_field: 'coding'}" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.pm2status" size="mini">
                        <el-option v-for="(item,statusIndex) in pm2Status" :key="statusIndex" :label="item" :value="statusIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">负责人</div>
                      <v-select-s v-model="query.admin_id" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">车 间</div>
                      <el-select v-model="query.workshop" size="mini" @change="factoryChange">
                        <el-option v-for="(item,workshopIndex) in planWorkshop" :key="workshopIndex" :label="item" :value="workshopIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">班 组</div>
                      <v-select v-model="query.member" action="classByFactory" :query="{factory: query.workshop}" multiple />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="4" :lg="4" :md="5" :sm="6" hidden>
                    <el-form-item>
                      <div class="search_label">安排时间</div>
                      <el-date-picker v-model="query.arrange_date" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">安排时间</div>
                      <el-date-picker v-model="query.arrange_date" type="datetimerange" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item>
                      <div class="search_label">安排时间</div>
                      <el-date-picker v-model="query.arrange" type="dates" placeholder="" value-format="yyyy-MM-dd HH:mm:ss" size="mini" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">操作者</div>
                      <v-select-s v-model="query.query_admin_id" action="adminList" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="专业点检导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" class="marginLeft20" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div v-if="tj" class="buttonBox">
                <el-button type="primary" icon="el-icon-box" size="mini" @click="archive">停产申请</el-button>
              </div>
              <div v-if="admin" class="buttonBox">
                <el-button type="primary" icon="el-icon-box" size="mini" @click="adminStop">停产审核</el-button>
              </div>
              <div v-if="admin" class="buttonBox">
                <el-button type="primary" icon="el-icon-box" size="mini" @click="adminNotStop">停产驳回</el-button>
              </div>
              <div class="buttonBox" :hidden="!canButton">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总数：<span>{{ total }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="pmList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" align="center" width="50" />
        <el-table-column type="selection" align="center" width="45" />
        <el-table-column prop="coding" label="编号" align="center" width="160" />
        <el-table-column label="名称" width="250">
          <template scope="scope">
            <span v-if="scope.row.eq">
              {{ scope.row.eq.coding }}-{{ scope.row.eq.name }}
            </span>
            <span v-else>已删除</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="" :formatter="statusFormat" />
        <el-table-column prop="workshop" label="车间" width="100" align="center" :formatter="workshopFormat" />
        <el-table-column prop="admin.name" label="负责人" min-width="80" align="center" />
        <el-table-column label="操作者" min-width="100" align="center">
          <template scope="scope">
            <span>{{ scope.row.other_member.map(item => {return item.admin.name}).join('，') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="plan" label="周期（天）" min-width="100" align="center">
          <template scope="scope">
            <span v-if="scope.row.plan">{{ scope.row.plan.period }}</span>
            <span v-else>计划已删除</span>
          </template>
        </el-table-column>
        <el-table-column prop="profession" label="专业" min-width="50" align="center" :formatter="professionFormat" />
        <el-table-column prop="priority" label="优先程度" min-width="80" align="center" :formatter="priorityFormat" />
        <el-table-column prop="arrange_date" label="安排时间" min-width="180" align="center" />
        <el-table-column prop="qrcode_time" label="扫码时间" min-width="180" align="center" />
        <el-table-column prop="submit_complate" label="完成时间" min-width="180" align="center" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="200" align="center">
          <template scope="scope">
            <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/maintain/pm5'
import { pm2Status, applyType, priority, planWorkshop } from '@/utils/options'
import VSelect from '@/components/select'
import VSelectS from '@/components/select-search'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
import { mapGetters } from 'vuex'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getModeFormat', 'getPlanWorkshopFormat', 'archives', 'getPlanProfessionFormat', 'getPlanPriorityFormat', 'getScope'],
  components: {
    VSelect,
    VSelectS
  },
  mixins: [exportMethod],
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      dialogTableVisible: false,
      needExport: [],
      needExportArray: ['编号', '资产', '车间', '负责人', '操作者', '类型', '周期', '状态', '安排时间', '扫码时间', '提交时间'],
      loading: false,
      pmList: [],
      total: 0,
      query: { page: 1, limit: 15, is_file: 1 },
      selection: [],
      pm2Status,
      applyType,
      priority,
      planWorkshop,
      tj: false,
      admin: false,
      canButton: false
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    },
    ...mapGetters([
      'userId'
    ])
  },
  watch: {},
  created() {
    if (this.getScope(this.userId) === 1) {
      this.canButton = true
    }
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()

    const scope = this.getScope(this.userId)
    if (scope === 1 || scope === 4 || this.userId === 148) {
      this.tj = true
    }

    if (scope === 1) {
      this.admin = true
    }
  },
  methods: {
    handleCheckAllChange(val) {
      this.needExport = val ? this.needExportArray : []
      this.isIndeterminate = false
    },
    handleText(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.needExportArray.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.needExportArray.length
    },
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    modeFormat(row) {
      return this.getModeFormat(row)
    },
    index() {
      this.loading = true
      API.pmList(this.query).then(response => {
        this.total = response.data.total
        this.pmList = response.data.data
      }).finally(() => {
        this.loading = false
      })
    },
    // 停产申请按钮
    archive() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.pmList(this.query).then(response => {
          this.selection = response.data.data
        }).finally(() => {
          this.commonStop(API, this.selection)
          this.loading = false
        })
      } else {
        this.commonStop(API, this.selection)
      }
    },
    // 停产申请接口
    commonStop(API, selection) {
      const ids = selection.map((item) => {
        return item.id
      }).join(',')
      API.archives({ ids }).then((res) => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '恭喜你，停产成功',
            type: 'success'
          })
          this.selection = []
          this.query.limit = 15
          this.query.page = 1
          this.index()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 停产审核按钮
    adminStop() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.pmList(this.query).then(response => {
          this.selection = response.data.data
        }).finally(() => {
          this.commonAdmin(this.selection)
          this.loading = false
        })
      } else {
        this.commonAdmin(this.selection)
      }
    },
    // 停产驳回按钮
    adminNotStop() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.pmList(this.query).then(response => {
          this.selection = response.data.data
        }).finally(() => {
          this.commonNotAdmin(this.selection)
          this.loading = false
        })
      } else {
        this.commonNotAdmin(this.selection)
      }
    },
    // 实际停产按钮
    commonAdmin(selection) {
      const ids = selection.map((item) => {
        return item.id
      }).join(',')
      API.adminStop({ ids }).then((res) => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '恭喜你，审核成功',
            type: 'success'
          })
          this.selection = []
          this.query.limit = 15
          this.query.page = 1
          this.index()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    commonNotAdmin(selection) {
      const ids = selection.map((item) => {
        return item.id
      }).join(',')
      API.adminNotStop({ ids }).then((res) => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '恭喜你，退回成功',
            type: 'success'
          })
          this.selection = []
          this.query.limit = 15
          this.query.page = 1
          this.index()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    remove() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const selection = this.selection
      this.delMany(API, selection)
    },
    confirmDel(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      this.delOne(API, id, false)
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/maintain/file_pm5_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      if (row.bz_check === 0 && row.engineer_check === 0) {
        // 无需审核
        if (row.status === 0) {
          return this.$createElement('div', { 'style': { 'color': 'blue' }}, '系统生成')
        } else if (row.status === 1) {
          return this.$createElement('div', { 'style': { 'color': 'green' }}, '执行完毕')
        }
      }
      if (row.bz_check === 1 && row.engineer_check === 0) {
        // 仅班长确认
        if (row.status === 0) {
          return this.$createElement('div', { 'style': { 'color': 'blue' }}, '系统生成')
        } else if (row.status === 1) {
          return this.$createElement('div', { 'style': { 'color': 'orange' }}, '待班长确认')
        } else if (row.status === 2) {
          return this.$createElement('div', { 'style': { 'color': 'green' }}, '执行完毕')
        }
      }
      if (row.bz_check === 0 && row.engineer_check === 1) {
        // 仅工程师确认
        if (row.status === 0) {
          return this.$createElement('div', { 'style': { 'color': 'blue' }}, '系统生成')
        } else if (row.status === 1) {
          return this.$createElement('div', { 'style': { 'color': 'orange' }}, '待工程师确认')
        } else if (row.status === 3) {
          return this.$createElement('div', { 'style': { 'color': 'green' }}, '执行完毕')
        }
      }
      if (row.bz_check === 1 && row.engineer_check === 1) {
        // 班长和工程师都需要确认
        if (row.status === 0) {
          return this.$createElement('div', { 'style': { 'color': 'blue' }}, '系统生成')
        } else if (row.status === 1) {
          return this.$createElement('div', { 'style': { 'color': 'orange' }}, '待班长确认')
        } else if (row.status === 2) {
          return this.$createElement('div', { 'style': { 'color': 'orange' }}, '待工程师确认')
        } else if (row.status === 3) {
          return this.$createElement('div', { 'style': { 'color': 'green' }}, '执行完毕')
        }
      }
      if (row.status === -1) {
        return this.$createElement('div', { 'style': { 'color': 'gray' }}, '待派发')
      }
      if (row.status === 10) {
        return this.$createElement('div', { 'style': { 'color': 'red' }}, '超时')
      }
      if (row.status === 99) {
        return this.$createElement('div', { 'style': { 'color': 'gray' }}, '归档')
      }
    },
    priorityFormat(row) {
      return this.getPlanPriorityFormat(row)
    },
    professionFormat(row) {
      return this.getPlanProfessionFormat(row)
    },
    workshopFormat(row) {
      return this.getPlanWorkshopFormat(row)
    },
    factoryChange(value) {
      if (value !== this.queryWorkshop) {
        this.query.member = null
        this.queryWorkshop = value
      }
    },
    exportHandler() {
      if (this.selection.length === 0) {
        this.query.limit = 90000
        this.loading = true
        API.pmList(this.query).then(response => {
          this.selection = response.data.data
        }).finally(() => {
          this.thisExport()
          this.loading = false
        })
      } else {
        this.thisExport()
      }
    },
    thisExport() {
      this.selection.forEach((item) => {
        if (item.type === 0) {
          item.typeOut = '设备'
        } else if (item.type === 1) {
          item.typeOut = '工装'
        }
        if (item.status === 0) {
          item.statusOut = '系统生成'
        } else if (item.status === 1) {
          item.statusOut = '完成'
        } else if (item.status === 10) {
          item.statusOut = '超时'
        }
        if (item.other_member) {
          if (item.other_member.length === 1) {
            item.memberOut = item.other_member[0].admin.name
          } else {
            item.memberOut = item.other_member.map(i => {
              return i.admin.name
            }).join(',')
          }
        }
        if (item.admin) {
          item.adminName = item.admin.name
        } else {
          item.adminName = '暂无'
        }
        if (item.eq) {
          item.eqOut = `${item.eq.coding}-${item.eq.name}`
        } else {
          item.eqOut = '已删除'
        }
        if (item.plan) {
          item.periodOut = item.plan.period
        } else {
          item.periodOut = '已删除'
        }
        if (item.workshop === 0) {
          item.workshopOut = '冲压车间'
        } else if (item.workshop === 1) {
          item.workshopOut = '车身车间'
        } else if (item.workshop === 2) {
          item.workshopOut = '涂装车间'
        } else if (item.workshop === 3) {
          item.workshopOut = '总装车间'
        } else if (item.workshop === 4) {
          item.workshopOut = '生产管理部'
        } else if (item.workshop === 5) {
          item.workshopOut = '质量部'
        } else if (item.workshop === 6) {
          item.workshopOut = '设备动力部'
        }
      })
      const data = []
      const titleObj = {
        'coding': '编号',
        'eqOut': '资产',
        'workshopOut': '车间',
        'adminName': '负责人',
        'memberOut': '操作者',
        'typeOut': '类型',
        'periodOut': '周期',
        'statusOut': '状态',
        'arrange_date': '安排时间',
        'qrcode_time': '扫码时间',
        'submit_complate': '提交时间'
      }
      if (this.needExport.length) {
        const title = []
        for (const key of this.needExport) {
          title.push(key)
        }
        data.push(title)
      } else {
        data.push(Object.values(titleObj))
      }
      const excelNeedExport = []
      for (const keys of this.needExport) {
        const thisKey = Object.keys(titleObj).find(key => titleObj[key] === keys)
        excelNeedExport.push(thisKey)
      }
      let fieldOut = 1
      this.selection.forEach((item) => {
        if (excelNeedExport.length) {
          const d = []
          for (const key of excelNeedExport) {
            if (key.includes('.')) {
              let value = item
              const tag = key.split('.')
              for (const k of tag) {
                value = value[k]
              }
              d.push(value)
            } else {
              d.push(item[key])
            }
          }
          data.push(d)
        } else {
          this.$message.error('请选择要到导出的字段')
          fieldOut = 2
        }
      })
      if (fieldOut === 1) {
        const workbook = {
          SheetNames: ['pm5'],
          Sheets: {
            'pm5': xlsx.utils.aoa_to_sheet(data)
          }
        }
        this.exportExec(workbook, '专业点检.xlsx')
        this.reload()
      }
    }
  }
}
</script>
